import Storage from '@/lib/storage';
const UUID_NAME = 'srx_distinct_id';

const storage = new Storage('localStorage');
/**
 * 唯一标识，清空localStorage后再次生成的跟上次不同
 * 并会存在本地的localStorage中
 */
const genUUID = (function () {
    var T = function () {
        var d = 1 * new Date(),
            i = 0;
        while (d == 1 * new Date()) {
            i++;
        }
        return d.toString(16) + i.toString(16);
    };
    var R = function () {
        return Math.random().toString(16).replace('.', '');
    };
    var UA = function (n) {
        var ua = navigator.userAgent,
            i,
            ch,
            buffer = [],
            ret = 0;

        function xor(result, byteArray) {
            var j,
                tmp = 0;
            for (j = 0; j < byteArray.length; j++) {
                tmp |= buffer[j] << (j * 8);
            }
            return result ^ tmp;
        }

        for (i = 0; i < ua.length; i++) {
            ch = ua.charCodeAt(i);
            buffer.unshift(ch & 0xff);
            if (buffer.length >= 4) {
                ret = xor(ret, buffer);
                buffer = [];
            }
        }

        if (buffer.length > 0) {
            ret = xor(ret, buffer);
        }

        return ret.toString(16);
    };

    return function () {
        var se = String(screen.height * screen.width);
        if (se && /\d{5,}/.test(se)) {
            se = se.toString(16);
        } else {
            se = String(Math.random() * 31242)
                .replace('.', '')
                .slice(0, 8);
        }
        var val = T() + '-' + R() + '-' + UA() + '-' + se + '-' + T();
        if (val) {
            return val;
        } else {
            return (
                String(Math.random()) +
                String(Math.random()) +
                String(Math.random())
            ).slice(2, 15);
        }
    };
})();

/**
 * 获取系统唯一标识，清空后会重新生成跟上次生成的值不同
 * @returns key
 */
function UUID() {
    let val = storage.getItem(UUID_NAME);
    if (!val) {
        val = genUUID();
        storage.setItem(UUID_NAME, val);
    }
    return val;
}

export { UUID };
export default UUID;
